package com.tdam2012.grupo04;



import java.util.ArrayList;
import java.util.List;

import com.tdam2012.grupo04.data.ActividadesProvider;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;

public class ActionsActivity extends ListActivity implements OnClickListener, OnItemClickListener {
	
	public static final String KEY_CONTACT = "Contact";
	public static String idC;
	private ActividadesAdapter _adapter;
	private static final String LLAMADA="Llamada";
	private static final String MENSAJETEXTO="Mensaje de texto";
	private static final String MENSAJEWEB="Mensaje web";
	private static final String EMAIL="Email";
	private static final String CRITERIOORDEN="criterioOrdenAcciones";
	private static final String FILTROACCIONES="filtrosAcciones";
	private static final String F0="F0";
	private static final String F1="F1";
	private static final String F2="F2";
	private static final String F3="F3";
	private static final String F4="F4";
	private static final String REC="Rec";
	private static final String DESC="DESC";
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_actions);
        getListView().setAdapter(new ActividadesAdapter());
        formatListView();
        loadData();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_actions, menu);
        menu.getItem(0).setIcon(android.R.drawable.ic_menu_preferences);
        menu.getItem(1).setIcon(android.R.drawable.ic_menu_set_as);
        
        return true;
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
    {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        menu.setHeaderTitle(getString(R.string.ActionsActivity_title));
        inflater.inflate(R.menu.menu_ctx_actionslist,menu);
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {   
    	
    	AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); 
    	switch (item.getItemId()) {
    		
    		case R.id.Opc1MenuContextualActionsActivity:
            	 String codAccion = _adapter.get_actividadesAdapter().get(info.position).getCodigo();
            	 if(eliminarAccion(codAccion)==1){
            		 //dialog q dice q se borro con exito la accion
            		 _adapter.get_actividadesAdapter().clear();
                	  cargarActividades(loadCriterPreferences(),loadSortPreferences());
                	 _adapter.notifyDataSetChanged();
            	 }
            	 else	 
            	 {
            		 //no se borro con exito la accion
            	 }
            	return true;
                
            default:
                return super.onContextItemSelected(item);
    		}
     }
    
    private int eliminarAccion(String codAccion){
    	try {
    	ContentResolver cr = getContentResolver();
    	return cr.delete(ActividadesProvider.CONTENT_URI, codAccion, null);
    	} catch (Exception e) {
    	return 0;
    	}
    }
  
    private void formatListView() {
		_adapter = new ActividadesAdapter();
		getListView().setAdapter(_adapter); 
		getListView().setOnItemClickListener(this);
		registerForContextMenu(getListView());
		
	}
    
   
  private void cargarActividades(String filtro, String orden) {
        ContentResolver cr = getContentResolver();
    	String idContacto = idC;
    	String[] condicion= new String[] {idContacto,filtro};
    	Cursor cursor = cr.query(ActividadesProvider.CONTENT_URI, null,ActividadesProvider.GET, condicion, orden);

		if (cursor.getCount() > 0) {
			while (cursor.moveToNext()) {
				String id =  cursor.getString(1);
				String tipo = cursor.getString(2);
				String fecha=cursor.getString(3);
				String codigo=cursor.getString(0);
				
				 Action actividad = new Action(id, tipo, fecha, codigo);
				_adapter.addActividad(actividad);
			}
		}
		cursor.close();
    }
    
    private void loadData()
    {
    	 
    	 Contact contacto = (Contact) getIntent().getSerializableExtra(ContactScreenActivity.KEY_CONTACT);
    	 idC= contacto.get_id();
    }
  
    protected void onResume() {
    	 super.onResume();
    	 _adapter.get_actividadesAdapter().clear();
    	 cargarActividades(loadCriterPreferences(),loadSortPreferences());
    	 _adapter.notifyDataSetChanged();
    }
    
    public String loadSortPreferences()
    {
    	SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    	String criterioOrden = pref.getString(CRITERIOORDEN, "");
    	if(criterioOrden.compareToIgnoreCase(REC) == 0){
    		criterioOrden = DESC;}
    	else{
    		criterioOrden = "";
    	}
    	return criterioOrden;
    }
    
    public String loadCriterPreferences()
    {
    	SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    	String criterioFiltro = pref.getString(FILTROACCIONES, "");
    	if(criterioFiltro.compareToIgnoreCase(F0)==0){
    		criterioFiltro = "";
    	}
    	if(criterioFiltro.compareToIgnoreCase(F1)==0){
    		criterioFiltro = LLAMADA;
    	}
    	if(criterioFiltro.compareToIgnoreCase(F2)==0){
    		criterioFiltro = MENSAJETEXTO;
    	}
    	if(criterioFiltro.compareToIgnoreCase(F3)==0){
    		criterioFiltro = MENSAJEWEB;
    	}
    	if(criterioFiltro.compareToIgnoreCase(F4)==0){
    		criterioFiltro = EMAIL;
    	}
    	
    	return criterioFiltro;
    }
    
   class Holder{
    	TextView txtFechayHora;
    	TextView txtTipoAccion;
    	String contactName;
    	String contactSecondName;
    }
    
    public class ActividadesAdapter extends BaseAdapter{
    	private List<Action> _actividadesAdapter;
		private LayoutInflater _inflater;
    	
    	public ActividadesAdapter(){
    		set_actividadesAdapter(new ArrayList<Action>());
    		this._inflater = LayoutInflater.from(ActionsActivity.this);
    		
    	}
    	public void addActividad(Action actividad)
    	{
    		get_actividadesAdapter().add(actividad);
    	}
    	
    	public Action getActividad(int position)
    	{
    		Action actividad =(Action)getItem(position);
    		return actividad;
    	}
    	
    	@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return get_actividadesAdapter().size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return get_actividadesAdapter().get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}
		public void clear(){
			_actividadesAdapter.clear();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			Holder holder = null;
			
			if(convertView == null){
				convertView = _inflater.inflate(R.layout.action_item,null);
				holder = new Holder();
				holder.txtFechayHora = (TextView) convertView.findViewById(R.id.txtFechayHora);
				holder.txtTipoAccion = (TextView) convertView.findViewById(R.id.txtTipoAccion);
				convertView.setTag(holder);
				
			} else {
				
				holder = (Holder) convertView.getTag();
			}
			
			Action ac= get_actividadesAdapter().get(position);
			String fecha=ac.getFecha();
			String tipo=ac.getTipoAccion();
			
			
			
			holder.txtFechayHora.setText(fecha);
			holder.txtTipoAccion.setText(tipo);
			return convertView;
		}
		
		private List<Action> get_actividadesAdapter() {
			return _actividadesAdapter;
		}
		private void set_actividadesAdapter(List<Action> _actividades) {
			this._actividadesAdapter = _actividades;
		}
    	
    	
    }

	@Override
	public void onClick(View v) {
	
	}
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
	
	}	
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		Intent i; 
		switch (item.getItemId()) {
		
		case R.id.ActionsItemMenu1:
			i = new Intent(this,ActionListPreferences.class );
			startActivity(i);
			break;
		case R.id.ActionsItemMenu2:
			i = new Intent(this,ConectividadListActivity.class);
			startActivity(i);
			break;
		default:
			break;
		}
		
		return super.onOptionsItemSelected(item);
	}
	
}
